<template>
  <div class="app-container">
    <el-button-group style="margin-bottom: 16px;">
      <el-button @click="goTo('/content/announcement')">公告管理</el-button>
      <el-button @click="goTo('/content/help')">帮助中心</el-button>
      <el-button @click="goTo('/content/carousel')">轮播图</el-button>
      <el-button @click="goTo('/system/basic')">系统配置</el-button>
    </el-button-group>
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="角色名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="Plus"
        @click="handleCreate"
      >
        新增角色
      </el-button>
    </div>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="角色ID" align="center" width="80">
        <template #default="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="角色名称" align="center" width="150">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="角色标识" align="center" width="150">
        <template #default="scope">
          <span>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="描述" min-width="200">
        <template #default="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="创建时间" align="center" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="350">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="warning"
            size="small"
            icon="Setting"
            @click="handlePermission(scope.row)"
          >
            权限设置
          </el-button>
          <el-button
            type="info"
            size="small"
            icon="User"
            @click="handleAssignUsers(scope.row)"
          >
            分配用户
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.page"
        v-model:page-size="listQuery.limit"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="600px"
    >
      <div v-if="currentRole">
        <p>为角色 <strong>{{ currentRole.name }}</strong> 设置权限：</p>
        <el-tree
          ref="permissionTree"
          :data="permissionData"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedPermissions"
          :props="{ label: 'name', children: 'children' }"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户分配对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="分配用户"
      width="600px"
    >
      <div v-if="currentRole">
        <p>为角色 <strong>{{ currentRole.name }}</strong> 分配用户：</p>
        <el-transfer
          v-model="selectedUsers"
          :data="userData"
          :titles="['可选用户', '已选用户']"
          :props="{
            key: 'id',
            label: 'username'
          }"
          @change="handleUserChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveUsers">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, post } from '@/utils/request'

const router = useRouter()

// 角色类型
interface Role {
  id: number
  name: string
  code: string
  description: string
  createTime: Date
  status: number
}

// 权限树类型
interface PermissionNode {
  id: number
  name: string
  children?: PermissionNode[]
}

// 用户类型
interface User {
  id: number
  username: string
  realName: string
  email: string
}

// 列表数据
const list = ref<Role[]>([])
const total = ref(0)
const listLoading = ref(true)

// 查询参数
const listQuery = reactive({
  page: 1,
  limit: 10,
  name: ''
})

// 角色相关变量
const currentRole = ref<Role | null>(null)
const permissionDialogVisible = ref(false)
const userDialogVisible = ref(false)
const permissionData = ref<PermissionNode[]>([])
const selectedPermissions = ref<number[]>([])
const userData = ref<User[]>([])
const selectedUsers = ref<number[]>([])

// 获取角色列表
const getList = async () => {
  listLoading.value = true
  try {
    const res = await get('/api/roles', listQuery)
    total.value = res.total
    list.value = res.items
  } catch (e) {
    ElMessage.error('获取角色失败')
  } finally {
    listLoading.value = false
  }
}

// 获取权限树数据
const getPermissionData = async () => {
  try {
    // 这里模拟API调用，实际项目中应替换为真实API
    // const res = await get('/api/permissions/tree')
    
    // 模拟权限树数据
    permissionData.value = [
      {
        id: 1,
        name: '系统管理',
        children: [
          { id: 11, name: '用户管理' },
          { id: 12, name: '角色管理' },
          { id: 13, name: '菜单管理' }
        ]
      },
      {
        id: 2,
        name: '内容管理',
        children: [
          { id: 21, name: '公告管理' },
          { id: 22, name: '帮助中心' },
          { id: 23, name: '轮播图管理' }
        ]
      },
      {
        id: 3,
        name: '数据管理',
        children: [
          { id: 31, name: '农户管理' },
          { id: 32, name: '商品管理' },
          { id: 33, name: '订单管理' }
        ]
      }
    ]
  } catch (error) {
    console.error('获取权限树失败:', error)
    ElMessage.error('获取权限树失败')
  }
}

// 获取用户列表
const getUserData = async () => {
  try {
    // 这里模拟API调用，实际项目中应替换为真实API
    // const res = await get('/api/users')
    
    // 模拟用户数据
    userData.value = Array.from({ length: 20 }).map((_, index) => ({
      id: index + 1,
      username: `用户${index + 1}`,
      realName: `真实姓名${index + 1}`,
      email: `user${index + 1}@example.com`
    }))
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 格式化日期
const formatDate = (date: string | number | Date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 搜索
const handleFilter = () => {
  listQuery.page = 1
  getList()
}

// 改变每页数量
const handleSizeChange = (val: number) => {
  listQuery.limit = val
  getList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  listQuery.page = val
  getList()
}

// 新增角色
const handleCreate = () => {
  router.push('/permission/role/add')
}

// 编辑角色
const handleUpdate = (row: Role) => {
  router.push(`/permission/role/edit/${row.id}`)
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', { type: 'warning' })
    await post('/api/roles/delete', { id: row.id })
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

// 更改角色状态
const handleStatusChange = async (row: Role) => {
  try {
    // 实际项目中替换为真实API调用
    // await post(`/api/roles/${row.id}/status`, { status: row.status })
    
    // 模拟操作成功
    ElMessage.success(`${row.status === 1 ? '启用' : '禁用'}成功`)
  } catch (error) {
    // 恢复状态
    row.status = row.status === 1 ? 0 : 1
    console.error('更改角色状态失败:', error)
    ElMessage.error('更改角色状态失败')
  }
}

// 打开权限设置对话框
const handlePermission = async (row) => {
  // 获取权限树和已选权限
  const res = await get('/api/roles/permissions', { roleId: row.id })
  permissionData.value = res.tree
  selectedPermissions.value = res.selected
  permissionDialogVisible.value = true
}

// 保存权限设置
const handleSavePermissions = async () => {
  await post('/api/roles/permissions/save', {
    roleId: currentRole.value.id,
    permissions: selectedPermissions.value
  })
  ElMessage.success('保存成功')
  permissionDialogVisible.value = false
}

// 打开用户分配对话框
const handleAssignUsers = async (row: Role) => {
  currentRole.value = row
  userDialogVisible.value = true
  // 获取所有用户
  const res = await get('/api/users')
  userData.value = res.list
  // 获取当前角色已分配用户
  const res2 = await get('/api/roles/users', { roleId: row.id })
  selectedUsers.value = res2.userIds
}

// 用户选择变化
const handleUserChange = (value: number[]) => {
  console.log('用户选择变化:', value)
}

// 保存用户分配
const handleSaveUsers = async () => {
  try {
    await post('/api/roles/users/save', {
      roleId: currentRole.value!.id,
      userIds: selectedUsers.value
    })
    ElMessage.success('用户分配成功')
    userDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('保存用户分配失败:', error)
    ElMessage.error('保存用户分配失败')
  }
}

// 组件挂载时获取列表数据
onMounted(() => {
  getList()
})

const goTo = (path: string) => router.push(path)
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-transfer {
  margin: 20px 0;
}
</style> 